package com.aispeech.asr.clib.vad;

import com.sun.jna.Native;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class Vad {
    private static IVad iVad = null;
    private long ptVad;

    public Vad(String resPath) {
//        log.info("respath: {}", resPath);
        ptVad = iVad.vad_new(resPath, 1);

        if (ptVad <= 0)
            throw new RuntimeException("vad_new failed. ptVad: " + ptVad);
    }

    public static void initialize() {
        iVad = Native.load("vad", IVad.class);
        log.info("Vad library loaded. iVad: {}", iVad);
    }

    public void addCallback(IVadNotifyCallback callback) {
        iVad.vad_register_handler(ptVad, 0, callback, 0, null);
    }
    
    public void addSpeechDataCallback(IVadDataCallback callback) {
        iVad.vad_register_speech_data_handler(ptVad, 0, callback);
    }

    public int start() {
        return start(500);
    }

    public int start(int pauseTime) {
        String config = String.format("{\"pauseTime\":%d}", pauseTime);

        iVad.vad_reset(ptVad);
        return iVad.vad_start(ptVad, config, config.length());
    }

    public int feed(byte[] data, int length) {
        int ret = 1;

        if (data.length > 0) {
            ret = iVad.vad_feed(ptVad, EParamState.APPEND.ordinal(), data, length);
            if (ret != 0) {
                log.warn("[ VAD ] feed err. ret: " + ret);
            }
//        } else {
//            log.warn("data is null");
        }

        return ret;
    }

    public int stop() {
        iVad.vad_flush(ptVad);
        return iVad.vad_end(ptVad);
    }

    public void destroy() {
        if (ptVad != 0)
            iVad.vad_delete(ptVad);

        ptVad = 0;
    }
}
